﻿using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using ACAD = Autodesk.AutoCAD.ApplicationServices;

using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;

using System;

using System.Linq;


namespace Plot08
{
public	class batchModify
	{
		[CommandMethod("oac", CommandFlags.Session)]
		public void _openAllDwgs()
		{
			ACAD.DocumentCollection d = ACAD.Application.DocumentManager;

			List<string> nameS_Dwgs = new List<string>();

			List<string> list_Dwgs = new List<string>();

			FolderBrowserDialog fold_Bro = new FolderBrowserDialog();

			Editor acEd_tmp = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;

			int FILEDIA = System.Convert.ToInt32(Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("FILEDIA"));

			Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("FILEDIA", 0);

			///存储和更改系统 变量

			int XREFNOTIFY = System.Convert.ToInt32(Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("XREFNOTIFY"));

			Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("XREFNOTIFY", 0);

			int PROXYNOTICE = System.Convert.ToInt32(Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("PROXYNOTICE"));

			Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("PROXYNOTICE", 0);


			List<string> str_infos = new List<string>();


			if (fold_Bro.ShowDialog() == DialogResult.OK) {

				string fold_str = fold_Bro.SelectedPath;

				list_Dwgs.Clear();

				foreach (var element in GetFileNames(fold_str, nameS_Dwgs, "")) {

					if (Path.GetExtension(element).Contains(".dwg")) {

						list_Dwgs.Add(element.ToString());

					}

				}

			}


			foreach (string fileName in list_Dwgs) {

				if (File.Exists(fileName)) {


#if CadVersion08

                    ACAD.Document doc = d.Open(fileName, false);

#elif CadVersion13


                    Autodesk.AutoCAD.DatabaseServices.Database tmpDb = new Autodesk.AutoCAD.DatabaseServices.Database(false, true);

                    tmpDb.ReadDwgFile(fileName, System.IO.FileShare.ReadWrite, true, null);

                    ACAD.Document doc = ACAD.Application.DocumentManager.GetDocument(tmpDb);


#endif



					try {
						//Delay(1000);

						if (ACAD.Application.DocumentManager.MdiActiveDocument.Name != doc.Name) {
							ACAD.Application.DocumentManager.MdiActiveDocument = doc;

						}

						//Plot08.PlotWin.Model_Plot();

						//using (DocumentLock acLockDoc = doc.LockDocument())
						//{
						//    Database db = doc.Database;

						//    Editor acEd = doc.Editor;

						//    Line l = new Line(new Point3d(0, 0, 0), new Point3d(0, 0, 0.5));

						//    ObjectId oid = AppendEntity(l, db);

						//}


						doc.Editor.WriteMessage("wfewewf");


#if CadVersion08

                        doc.CloseAndSave(fileName);

#elif CadVersion13

                        Autodesk.AutoCAD.ApplicationServices.DocumentExtension.CloseAndSave(doc, fileName);


#endif

					} catch (System.Exception) {

						Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("有疑问发生");

#if CadVersion08

                        doc.CloseAndSave(fileName);

#elif CadVersion13

                        Autodesk.AutoCAD.ApplicationServices.DocumentExtension.CloseAndSave(doc, fileName);

#endif

					}


				} else {

					ACAD.Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("\nDrawing can not be found !");

				}

			}

			Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("XREFNOTIFY", XREFNOTIFY);

			Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("PROXYNOTICE", PROXYNOTICE);

			Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("FILEDIA", FILEDIA);

		}

		/// <summary>  
		/// 获取路径下所有文件以及子文件夹中文件  
		/// </summary>  
		/// <param name="path">全路径根目录</param>  
		/// <param name="FileList">存放所有文件的全路径</param>  
		/// <param name="RelativePath"></param>  
		/// <returns></returns>  
		public static List<string> GetFileNames(string path, List<string> FileList, string RelativePath)
		{
			DirectoryInfo dir = new DirectoryInfo(path);

			FileInfo[] fil = dir.GetFiles();

			DirectoryInfo[] dii = dir.GetDirectories();

			foreach (FileInfo f in fil) {
				//int size = Convert.ToInt32(f.Length);  
				FileList.Add(f.FullName);//添加文件路径到列表中  
			}
			//获取子文件夹内的文件列表，递归遍历  
			foreach (DirectoryInfo d in dii) {

				GetFileNames(d.FullName, FileList, RelativePath);

			}

			return FileList;

		}
		
		
		
		
		void ModifyGivenNamedTagValue(string tag_str, string val_str, BlockReference block_Ref)
		{

			Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

			Editor acEd = doc.Editor;

			using (Transaction acTrans = doc.Database.TransactionManager.StartTransaction()) {
		

				// 以写的方式打开选择的对象   Open the selected object for write
//
//						Entity A_ent = acTrans.GetObject(idArray[i], OpenMode.ForWrite) as Entity;
				
//				block_Ref.UpgradeOpen();
				


				foreach (ObjectId att_id in block_Ref.AttributeCollection) {
					
					AttributeReference attRef = acTrans.GetObject(att_id, OpenMode.ForWrite, false) as AttributeReference;

					if (attRef.Tag.ToString() == tag_str) {

						attRef.TextString = val_str;

					}

				}

						

				acTrans.Commit();
			}

				

			

		}
		
		
        
        
        
		/// <summary>
		/// 批量打印已经打开文档图纸空间的所有图框块
		/// </summary>
		[CommandMethod("xgri", CommandFlags.Session)]
		public void _Modify_All_Dwgs()
		{

			List<string> nameS_Dwgs = new List<string>();

			List<string> list_Dwgs = new List<string>();

			Editor acEd_tmp = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;

			ACAD.DocumentCollection docColS = ACAD.Application.DocumentManager;
            
			#region 排序文档名称
    
			List<Document> noSortdocCol = new List<Document>();
            
			foreach (Document element in docColS) {
            	
				noSortdocCol.Add(element);
            	
			}
            
			noSortdocCol.OrderBy(d => d.Name);
            
            
			List<Document> docCol = new List<Document>();
             
            
			docCol = noSortdocCol.ToList();
            
			foreach (var element in docCol) {
            	
				acEd_tmp.WriteMessage(element.Name + "\n");
             	
			}
  
			string activeFileName = string.Empty;
   
			#endregion


			#region 获取图框块名称记录文件Tk.xml及页面设置所在的dwg文件路径.

			string dwgFilePath = "";

			string sAssemblyPath = System.Reflection.Assembly.GetExecutingAssembly().Location;

			string shortNameDllFileName = System.IO.Path.GetFileName(sAssemblyPath);

			dwgFilePath = sAssemblyPath.Replace(shortNameDllFileName, "DeaufltPlotSetings.dwg");

			string xmlFilePath = string.Empty;

			xmlFilePath = sAssemblyPath.Replace(shortNameDllFileName, "Tk.xml");

			#endregion

			#region 读入TK.xm文件中的记录的图框块名称到blockNames

			List<string> blockNames = new List<string>();

			if (System.IO.File.Exists(xmlFilePath)) {

				XmlTool Tool = new XmlTool(xmlFilePath);

				foreach (var item in Tool.Get_TkNameInfo()) {
					blockNames.Add(item);
				}

			} else {
				ACAD.Application.ShowAlertDialog("没有找到图框块名称记录文件Tk.xml,程序无法运行");

				return;

			}

			#endregion

  

			foreach (var item in docCol) {
				
				List<ObjectId> layoutIds = new List<ObjectId>();

				List<Layout> layouts = new List<Layout>();

				Document dItem = item as Document;

				#region 统一当前工作数据库与当前显示文档,如果不统一会报错的
				try {

					if (HostApplicationServices.WorkingDatabase != dItem.Database) {

						HostApplicationServices.WorkingDatabase = dItem.Database;

						docColS.MdiActiveDocument = dItem;

					}

				} catch (Autodesk.AutoCAD.Runtime.Exception e) {

					ACAD.Application.ShowAlertDialog("当前文档与当前数据库不对应，程序出错" + e.Message.ToString());

					return;
				}
      
				activeFileName = dItem.Name;
                
       
				#endregion
                
                

				using (dItem.LockDocument()) {
					
					
					Database acDb = dItem.Database;
                
					using (Transaction acTrans = acDb.TransactionManager.StartTransaction()) {


					  	
						List<BlockReference> blocks = new List<BlockReference>();
                            
                            
						blocks = LayoutTool.Get_tk_BlocksAuto(blockNames);
                            
						foreach (var blockItem in blocks) {
                            	
                            	
							ModifyGivenNamedTagValue("日期","2020.04",blockItem);
                            		
						}
                            
                            

						acTrans.Commit();
                   

					}


				}



        #if CadVersion08

                        //dItem.CloseAndSave(dItem.Name);

#elif CadVersion13

                        //Autodesk.AutoCAD.ApplicationServices.DocumentExtension.CloseAndSave(dItem, dItem.Name);


#endif
        
     
        
        


			}
		}
        
	}
}
